import store from '@/store';
import * as $apis from '@/apis/index.js';

// 微信公众号授权
export function wxAuthorize(redirect_uri = '') {
	return new Promise((resolve, reject) => {
		// 非静默授权，第一次有弹框
		let local = window.location.href; // 获取页面url
		let pages = getCurrentPages();
		let route = "";
		if (pages.length == 1) {
			route = '/pages/tabbar/home/index';
		} else {
			let prePage = pages[pages.length - 2];
			if (prePage.__page__ && prePage.__page__.fullPath) {
				route = prePage.__page__.fullPath;
			} else {
				route = prePage.route;
			}
		}
		let redirectUri = redirect_uri || `${location.origin}/pages/common_page/login/loading?path=${encodeURIComponent(route)}`;
		redirectUri = encodeURIComponent(redirectUri);
		// window.location.href = decodeURIComponent(redirectUri);
		// return
		let state = encodeURIComponent(
			("" + Math.random()).split(".")[1] + "authorizestate"
		);
		let appid = 'appid'; // 公众号appid
		let code = getUrlCode().code; // 截取code
		// 获取之前的code
		let oldCode = uni.getStorageSync('wechatCode')
		if (code == null || code === '' || code == 'undefined' || code == oldCode) {
			// 如果没有code，就去请求获取code
			// console.log('当前没有code，进入授权页面')
			let uri = encodeURIComponent(local)
			$apis.getJSSDK({
				url: uri,
				apiLoadText: '登录中'
			}).then((res) => {
				let resParse = JSON.parse(res)
				// console.log(resParse.appId)
				appid = resParse.appId
				// 设置旧的code为0，避免死循环
				uni.setStorageSync('wechatCode', 0)
				window.location.href =
					`https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${redirectUri}&response_type=code&scope=snsapi_userinfo&state=${state}#wechat_redirect`
			})
		} else {
			// console.log('存在code，使用code换取用户信息')
			// 保存最新code
			uni.setStorageSync('wechatCode', code)
			$api.officialLogin({
				code
			}).then((res) => {
				resolve(res)
			})
		}
	})
}

export function getUrlCode() {
	// 截取url中的code方法
	var url = location.search;
	// this.winUrl = url;
	var theRequest = new Object();
	if (url.indexOf('?') != -1) {
		var str = url.substr(1);
		var strs = str.split('&');
		for (var i = 0; i < strs.length; i++) {
			theRequest[strs[i].split('=')[0]] = strs[i].split('=')[1];
		}
	}
	return theRequest;
}
